package indi.a709924470.scpwiki;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Ref;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import indi.a709924470.scpwiki.RecycleViewThings.itemDecorate;
import indi.a709924470.scpwiki.beans.TheBean;
import indi.a709924470.scpwiki.beans.WikiItems;
import indi.a709924470.scpwiki.RecycleViewThings.rcvwHolder;
import indi.a709924470.scpwiki.beans.WikiSubItems;

public class MainPageActivity extends AppCompatActivity {
    public static String openurl = null;
    private static rcvwHolder rh = null;
    private List<WikiItems> lw = null;
    private SwipeRefreshLayout srf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
        //startActivity(new Intent(this, HackIn.class));
        this.setTitle("SCP DOC SERVER@root");
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (!isNetworkAvailable(this))
            Toast.makeText(this, "无网络连接！", Toast.LENGTH_LONG).show();
            //Snackbar.make(getWindow().getDecorView().getRootView(), "无网络连接！", Snackbar.LENGTH_INDEFINITE);
        try {
            ExecutorService es = Executors.newSingleThreadExecutor();
            Future<Boolean> fb = es.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    InetAddress ina = null;
                    ina = InetAddress.getByName("scp-wiki-cn.wikidot.com");
                    return ina != null;
                }
            });
            if(!fb.get()){
                throw new Exception("No NetWork!");
            }
        }catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "无网络连接！", Toast.LENGTH_LONG).show();
        }

        /*try{
            ParseWikiPage pwp = new ParseWikiPage(null,null);
            if (!pwp.isSuccess()){
                WikiItems wi = new WikiItems();
                wi.setName("刷新失败...QAQ");
                lw.add(wi);
                throw new Exception(pwp.getError());
            }else {
                lw = pwp.sideitems();
                Toast.makeText(this,"加载失败...",Toast.LENGTH_LONG);
            }

            Log.d("INFO", "onCreate: Created.");
            if (lw == null){
                Log.w("Warning!", "onCreate: lw is null!");
            }else{
                Log.d("INFO", "onCreate: lw.length = "+lw.size());
            }
        }catch (Exception e){
            e.printStackTrace();
        }*/

        rh = new rcvwHolder(lw,this,HolderType.MainPage);
        RecyclerView rv = (RecyclerView) findViewById(R.id.mainRV);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new itemDecorate(this, LinearLayout.HORIZONTAL,1, ContextCompat.getColor(this,R.color.subline)));
        rv.setAdapter(rh);
        rh.notifyDataSetChanged();

        srf = (SwipeRefreshLayout) findViewById(R.id.srl);
        srf.setDistanceToTriggerSync(100);
        srf.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_bright));
        srf.setColorSchemeColors(Color.GREEN,Color.BLUE,Color.YELLOW,Color.RED);
        srf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Refresh().execute("");
            }
        });

        srf.setRefreshing(true);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "正在刷新......", Snackbar.LENGTH_SHORT)
                        .setAction("Action", null).show();
                new Refresh().execute("");
            }
        });
    }

    public String readAsset(String file){
        try {
            InputStream is = getAssets().open(file);
            int size = is.available();
            byte[] buffer= new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null){
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    class Refresh extends AsyncTask<String,Void,Boolean>{

        @Override
        protected void onPreExecute(){
            srf.setRefreshing(true);
        }

        @Override
        protected Boolean doInBackground(String... strings) {
            Log.d("Refresh", "doInBackground: Now Refreshing...");
            try {
                ParseWikiPage pwp = new ParseWikiPage(strings[0] == "" ? null : strings[0],"");
                if(!pwp.isSuccess()) {
                    Log.d("Refresh", "doInBackground: Not Success.");
                    return false;
                }
                lw = pwp.pageitems();
                Log.d("Refresh", "doInBackground: successed, lw length = "+lw.size());
                rh.notifyDataSetChanged();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result){
            srf.setRefreshing(false);
            if(!result){
                Toast.makeText(getApplicationContext(),"加载失败，请重试!",Toast.LENGTH_LONG);
            }
        }
    }
/*
    class netTest extends AsyncTask<Void,Void,Boolean>{

        @Override
        protected Boolean doInBackground(Void... voids) {
            try {
                InetAddress ia = InetAddress.getByName("scp-wiki-cn.wikidot.com");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }

    class SubTask extends AsyncTask<TheBean,Void,TheBean[]>{

        @Override
        protected TheBean[] doInBackground(TheBean... beans) {
            TheBean[] newBean = new TheBean[beans.length];
            List<TheBean> bs = new ArrayList<>();
            for (int i = 0; i < beans.length; ++i){
                TheBean tb = beans[i];
                String url = tb.getString();
                List<WikiItems> lw = tb.getItemList();
                List<WikiSubItems> lws = tb.getSubList();
                List<WikiItems> tlw = new ArrayList<>();
                List<WikiSubItems> tls = new ArrayList<>();
                String ts = null;
                if(url != null){
                    ParseWikiPage pwp = new ParseWikiPage(url,null);
                    if(!pwp.isSuccess()) {
                        tlw = null;
                        ts = "Failed";
                    }else if (url=="") {
                        tlw = pwp.sideitems();
                        ts = "Side";
                    }else {
                        tlw = pwp.pageitems();
                        ts = "Page";
                    }
                }
                bs.add(new TheBean(tlw,tls,ts));
            }
            bs.toArray(newBean);
            return newBean;
        }

        @Override
        protected void onPostExecute(TheBean[] result){
        }
    }*/
}
